package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"gozabbix/conf"
	"gozabbix/zabbix"

	"github.com/gin-gonic/gin"
)

/*
需求: 获取zabbix最近的告警事件
1. 通过登录方法获取接口凭证
2. 通过触发器方法获取已经触发的不同级别的问题事件
*/

// https://www.zabbix.com/documentation/3.4/zh/manual/api

// 第二个例子其实已经说明,只需要补充额外的条件即可满足需求
// https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get
// https://blog.csdn.net/honux5i/article/details/78612469

var (
	c string
	p string
	f *os.File
)

func init() {
	flag.StringVar(&c, "c", "conf.yml", "configuration file, default cfg.yaml")
	flag.StringVar(&p, "p", "9099", "listen port, default 9099")
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	var err error
	f, err = os.OpenFile("zbx.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(f)
}

func main() {
	flag.Parse()
	cfg := conf.LoadFile(c)
	// MinSeverity : Return only triggers with severity greater or equal than the given severity.
	// severity : Disaster(5)、 High(4)、 Average(3)、 Warning(2)、 Information(1)、 Not classified(0)
	zbx := zabbix.New(cfg.URL, cfg.User, cfg.Password, cfg.MinSeverity)
	err := zbx.Login()
	if err != nil {
		return
	}

	gin.SetMode(gin.ReleaseMode)
	gin.DefaultWriter = f
	r := gin.Default()
	r.LoadHTMLFiles("index.html")
	// just for test
	r.GET("/", func(c *gin.Context) {
		c.String(200, "hi")
	})

	r.GET("/zbx", func(c *gin.Context) {
		problem := zbx.GetLastProblem()
		c.HTML(200, "index.html", problem)
	})
	r.GET("/zbx/:group", func(c *gin.Context) {
		problem := zbx.GetProblemByGroup(c.Param("group"))
		c.HTML(200, "index.html", problem)
	})
	fmt.Println("start listen", p)
	log.Println("start listen", p)
	r.Run(fmt.Sprintf(":%v", p))
}
